//上传
const Router = require('koa-router')
const router = new Router()
const orm = require('../utils/mysql')
const fs = require('fs');
const image = require('../model/image')

router.prefix('/upload')

router.get('/all', async (ctx, next) => {
	var query = () => {
		return new Promise((resolve, rject) => {

			var Image = orm.db.define("fruit_images", image, {
				methods: {
					fullName: function() {
						return this.name + ' ' + this.surname;
					}
				},
				validations: {
					age: orm.enforce.ranges.number(18, undefined, "under-age")
				}
			});

			Image.find({

			}, function(err, image) {
				if (err) {
					resolve({
						code: 400,
						msg: err
					})
				}
				resolve({
					code: 200,
					obj: image
				})
			})


		})
	}
	var result = await query();
	ctx.body = result;
});

//路由
router.post('/add', async (ctx, next) => {


	var fs = require('fs');　　　　
	var path = './public/uploads/' + Date.now() + '.png'; //从app.js级开始找--在我的项目工程里是这样的

	var dataBuffer = new Buffer(ctx.request.body.file, 'base64'); //把base64码转成buffer对象，
	console.log('dataBuffer是否是Buffer对象：' + Buffer.isBuffer(dataBuffer));
	var query = () => {
		return new Promise((resolve, rject) => {
			fs.writeFile(path, dataBuffer, function(err) { //用fs写入文件
				if (err) {
					console.log(err);
				} else {
					var Image = orm.db.define("fruit_images", image, {
						methods: {
							fullName: function() {
								return this.name + ' ' + this.surname;
							}
						},
						validations: {
							age: orm.enforce.ranges.number(18, undefined, "under-age")
						}
					});
					var json = {
						name: ctx.request.body.name,
						url: 'http://172.16.21.227:3000' + path.split('public')[1],
						yn: 0
					}
					console.log(json)
					Image.create(json, function(err, image) {
						if (err) {
							resolve({
								code: 400,
								msg: err
							})
						}
						Image.find({

						}, function(err, image) {
							if (err) {
								resolve({
									code: 400,
									msg: err
								})
							}
							resolve({
								code: 200,
								obj: image
							})
						})

					})

					// resolve(json)
				}
			});
		})
	}
	var result = await query()
	ctx.body = result
})

module.exports = router